package com.jt.base.utils;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author longheping
 * @date 2018/11/2 10:04
 */
public class ExportUtil {

    /**
     * 导出到流
     */
    public static void exportExcel(HttpServletRequest request,
                                   HttpServletResponse response, List<List<Object>> rows) throws IOException {
        ExcelWriter writer = ExcelUtil.getBigWriter();
        writer.write(rows);
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        response.setContentType("application/vnd.ms-excel");
        String fileName = "防伪码";
        //google,火狐浏览器
        if (StringUtils.contains(agent, "firefox")) {
            fileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
        } else {
            //其他浏览器
            fileName = java.net.URLEncoder.encode(fileName, "UTF8");
        }
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out);
        writer.close();
    }

    /**
     * 导出到文件
     */
    public static void exportExcelToFile(String title, List<List<String>> rows, String filePath)
            throws IOException {
        ExcelWriter writer = ExcelUtil.getBigWriter(filePath);
        writer.merge(rows.size() - 1, title);
        writer.write(rows);
        writer.close();
    }
}
